<!-- 
===== 地图绘制功能切换说明 =====
如需启用地图绘制功能（直接在地图上绘制），请：
1. 取消注释下方标记为 [MAP_DRAWING] 的代码块
2. 注释掉标记为 [POPUP_DRAWING] 的代码块
3. 在 main.ts 中取消注释 MapboxDraw CSS 导入
4. 在 index.vue 中取消注释 DrawingManager 初始化代码
================================ 
-->
<template>
    <div class="edit-mode">
      <div class="edit-header">
        <div class="edit-title">
          <span
            class="edit-title-text"
            :title="
              editingItem
                ? editingItem.name || editingItem.communityName
                : '新增项目'
            "
          >
            {{
              editingItem
                ? editingItem.name || editingItem.communityName
                : '新增项目'
            }}
          </span>
          <span
            class="edit-status"
            :style="{
              backgroundColor: statusOptions.find(
                (option) => option.value == editingItem.status
              )?.color,
            }"
            v-if="editingItem"
            >{{
              statusOptions.find((option) => option.value == editingItem.status)
                ?.label
            }}</span
          >
        </div>
  
        <div class="edit-actions">
          <el-popconfirm title="确定删除吗？" @confirm="handleDelete">
            <el-button
              type="danger"
              size="mini"
              slot="reference"
              v-if="editingItem && !detailMode"
              icon="el-icon-delete"
              circle
            ></el-button>
          </el-popconfirm>
  
          <el-button
            type="default"
            size="mini"
            icon="el-icon-back"
            circle
            @click="handleCancel"
          ></el-button>
        </div>
      </div>
  
      <el-form
        ref="editFormRef"
        :model="formData"
        :rules="formRules"
        class="edit-form"
        label-position="top"
      >
        <template v-for="item in formItems">
          <el-form-item
            v-if="item.type === 'input' && shouldShowChildItem(item)"
            :key="`input-${item.pkid}`"
            :prop="item.pkid"
            :label="item.problemContent"
          >
            <template v-if="!detailMode">
              <el-input
                v-model="formData[item.pkid]"
                :placeholder="item.hint"
                :type="
                  item.problemType === '13' || item.problemType === '14'
                    ? 'number'
                    : 'text'
                "
                clearable
              >
                <template v-if="item.unit" #suffix>{{ item.unit }}</template>
              </el-input>
            </template>
            <template v-else>
              <span>{{ formData[item.pkid] || '-' }}</span>
            </template>
          </el-form-item>
  
          <el-form-item
            v-if="item.type === 'textarea' && shouldShowChildItem(item)"
            :key="`textarea-${item.pkid}`"
            :prop="item.pkid"
            :label="item.problemContent"
          >
            <template v-if="!detailMode">
              <el-input
                v-model="formData[item.pkid]"
                type="textarea"
                :rows="3"
                :placeholder="item.hint"
                clearable
              />
            </template>
            <template v-else>
              <span style="white-space: pre-line">{{
                formData[item.pkid] || '-'
              }}</span>
            </template>
          </el-form-item>
  
          <el-form-item
            v-if="item.type === 'radio' && shouldShowChildItem(item)"
            :key="`radio-${item.pkid}`"
            :prop="item.pkid"
            :label="item.problemContent"
          >
            <template v-if="!detailMode">
              <el-radio-group v-model="formData[item.pkid]">
                <el-radio
                  v-for="option in item.problemContentInfoList"
                  :key="option.pkid"
                  :label="option.pkid"
                >
                  {{ option.content }}
                </el-radio>
              </el-radio-group>
            </template>
            <template v-else>
              <span>
                {{
                  (
                    item.problemContentInfoList.find(
                      (opt) => opt.pkid == formData[item.pkid]
                    ) || {}
                  ).content || '-'
                }}
              </span>
            </template>
          </el-form-item>
  
          <el-form-item
            v-if="item.type === 'checkbox' && shouldShowChildItem(item)"
            :key="`checkbox-${item.pkid}`"
            :prop="item.pkid"
            :label="item.problemContent"
          >
            <template v-if="!detailMode">
              <el-checkbox-group v-model="formData[item.pkid]">
                <el-checkbox
                  v-for="option in item.problemContentInfoList"
                  :key="option.pkid"
                  :label="option.pkid"
                >
                  {{ option.content }}
                </el-checkbox>
              </el-checkbox-group>
            </template>
            <template v-else>
              <span>
                <template
                  v-if="
                    Array.isArray(formData[item.pkid]) &&
                    formData[item.pkid].length
                  "
                >
                  {{
                    formData[item.pkid]
                      .map(
                        (val) =>
                          (
                            item.problemContentInfoList.find(
                              (opt) => opt.pkid == val
                            ) || {}
                          ).content
                      )
                      .filter(Boolean)
                      .join('，')
                  }}
                </template>
                <template v-else>-</template>
              </span>
            </template>
          </el-form-item>
          <el-form-item
            v-if="item.type === 'date-picker' && shouldShowChildItem(item)"
            :key="`date-picker-${item.pkid}`"
            :prop="item.pkid"
            :label="item.problemContent"
          >
            <template v-if="!detailMode">
              <el-date-picker
                v-model="formData[item.pkid]"
                type="date"
                value-format="yyyy-MM-dd"
                :placeholder="item.hint"
                clearable
              >
              </el-date-picker>
            </template>
            <template v-else>
              <span>{{ formData[item.pkid] || '-' }}</span>
            </template>
          </el-form-item>
  
          <el-form-item
            v-if="item.type === 'image-upload' && shouldShowChildItem(item)"
            :key="`image-${item.pkid}`"
            :prop="item.pkid"
            :label="item.problemContent"
          >
            <template v-if="!detailMode">
              <el-upload
                action=""
                list-type="picture-card"
                :file-list="formData[item.pkid] || []"
                :http-request="() => {}"
                :before-upload="(file) => handleImageUpload(file, item.pkid)"
                :on-remove="(file) => handleImageRemove(file, item.pkid)"
                :multiple="false"
                accept="image/*"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <div v-if="item.limitCondition" class="upload-limit">
                至少上传 {{ item.limitCondition }} 张照片
              </div>
            </template>
            <template v-else>
              <div v-if="formData[item.pkid] && formData[item.pkid].length">
                <el-image
                  v-for="img in formData[item.pkid]"
                  :key="img.id"
                  :src="img.url"
                  style="width: 80px; margin-right: 8px"
                  :preview-src-list="formData[item.pkid].map((i) => i.url)"
                />
              </div>
              <span v-else>无</span>
            </template>
          </el-form-item>
  
          <el-form-item
            v-if="item.type === 'draw' && shouldShowChildItem(item)"
            :key="`draw-${item.pkid}`"
            :prop="item.pkid"
            :label="item.problemContent"
          >
            <template v-if="!detailMode">
              <!-- [POPUP_DRAWING] - 弹窗绘制按钮（当前启用） -->
              <!-- <el-button 
                type="primary" 
                @click="() => handleStartDraw(item)"
              >
                {{ formData[item.pkid] ? '重新绘制' : item.problemContent }}
              </el-button>
              <span v-if="formData[item.pkid]" class="draw-info"> 
                <span>{{ getDrawStatusText(item) }} </span>
              </span> -->
              
              <!-- [MAP_DRAWING] - 地图绘制按钮（注释掉） -->
              <el-button 
                type="primary" 
                @click="() => handleStartDraw(item)"
                :disabled="isDrawingMode && currentDrawItem && currentDrawItem.pkid !== item.pkid"
              >
                {{ formData[item.pkid] ? '重新绘制' : item.problemContent }}
              </el-button>
              <el-button
                v-if="isDrawingMode && currentDrawItem && currentDrawItem.pkid === item.pkid"
                type="danger"
                @click="handleCancelDrawing"
                style="margin-left: 10px"
              >
                取消绘制
              </el-button>
              <span v-if="formData[item.pkid] && !isDrawingMode" class="draw-info"> 
                <span>{{ getDrawStatusText(item) }} </span>
              </span>
            </template>
            <template v-else>
              <span v-if="formData[item.pkid]">{{ getDrawStatusText(item) }}</span>
              <span v-else>-</span>
            </template>
          </el-form-item>
  
          <el-form-item
            v-if="item.type === 'building-choose' && shouldShowChildItem(item)"
            :key="`building-${item.pkid}`"
            :prop="item.pkid"
            :label="item.problemContent"
          >
            <template v-if="!detailMode">
              <div class="building-selection-container">
                <el-button
                  type="primary"
                  @click="() => handleChooseBuilding(item)"
                  :disabled="
                    isBuildingSelectionMode &&
                    currentBuildingItem &&
                    currentBuildingItem.pkid !== item.pkid
                  "
                >
                  {{ formData[item.pkid] ? '重新选择' : item.problemContent }}
                </el-button>
                <el-button
                  v-if="
                    isBuildingSelectionMode &&
                    currentBuildingItem &&
                    currentBuildingItem.pkid === item.pkid
                  "
                  type="success"
                  @click="() => handleCompleteBuildingSelection(item)"
                  style="margin-left: 10px"
                >
                  完成选中
                </el-button>
                <el-button
                  v-if="
                    isBuildingSelectionMode &&
                    currentBuildingItem &&
                    currentBuildingItem.pkid === item.pkid
                  "
                  type="default"
                  @click="handleCancelBuildingSelection"
                  style="margin-left: 10px"
                >
                  清空选择
                </el-button>
                <span v-if="formData[item.pkid]" class="building-info">
                  已选择{{ item.problemType === '30' ? '多个' : '' }}建筑 ({{
                    getBuildingCount(item.pkid)
                  }}个)
                </span>
              </div>
            </template>
            <template v-else>
              <span>
                <template
                  v-if="formData[item.pkid] && getBuildingCount(item.pkid)"
                >
                  已选择{{ item.problemType === '30' ? '多个' : '' }}建筑 ({{
                    getBuildingCount(item.pkid)
                  }}个)
                </template>
                <template v-else>-</template>
              </span>
            </template>
          </el-form-item>
  
          <el-form-item
            v-if="item.type === 'floor-choose' && shouldShowChildItem(item)"
            :key="`floor-${item.pkid}`"
            :prop="item.pkid"
            :label="item.problemContent"
          >
            <template v-if="!detailMode">
              <el-button type="primary" @click="() => handleChooseFloor(item)">
                {{ formData[item.pkid] ? '重新选择' : item.problemContent }}
              </el-button>
              <span v-if="formData[item.pkid]" class="floor-info">
                已选择楼层
              </span>
            </template>
            <template v-else>
              <span v-if="formData[item.pkid]">已选择楼层</span>
              <span v-else>-</span>
            </template>
          </el-form-item>
  
          <el-form-item
            v-if="item.type === 'region-select' && shouldShowChildItem(item)"
            :key="`region-${item.pkid}`"
            :prop="item.pkid"
            :label="item.problemContent"
          >
            <template v-if="!detailMode">
              <el-cascader
                v-model="formData[item.pkid]"
                :options="item.areaList || cityOptions"
                :props="cascaderProps"
                :placeholder="item.hint"
                clearable
                filterable
                :show-all-levels="false"
              />
            </template>
            <template v-else>
              <span>
                <template
                  v-if="
                    Array.isArray(formData[item.pkid]) &&
                    formData[item.pkid].length
                  "
                >
                  {{ getRegionLabel(item, formData[item.pkid]) }}
                </template>
                <template v-else>-</template>
              </span>
            </template>
          </el-form-item>
        </template>
  
        <div class="form-actions" v-if="!detailMode">
          <el-button type="primary" @click="handleSave">保存</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </div>
      </el-form>
  
      <!-- [POPUP_DRAWING] - 弹窗绘制组件 -->
      <!-- <DrawMap
        :visible="showDrawTool"
        title="位置绘制"
        :type="currentDrawItem?.problemType"
        :data="getDrawMapData()"
        @update="handleDrawEnd"
        @close="handleCloseDrawTool"
      /> -->
    </div>
  </template>
  
  <script>
  import { Message } from 'element-ui'
  import { uploadFile } from '@/api/question'
  import emitter from '@/utils/event-bus'
  // import DrawMap from '@/components/draw-map' // [POPUP_DRAWING]
  
  export default {
    name: 'EditForm',
    components: {
      // DrawMap, // [POPUP_DRAWING]
    },
    props: {
      editingItem: {
        type: Object,
        default: null,
      },
      cityOptions: {
        type: Array,
        default: () => [],
      },
      statusOptions: {
        type: Array,
        default: () => [],
      },
      detailMode: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        cascaderProps: {
          value: 'pkid',
          label: 'areaName',
          checkStrictly: true,
          children: 'children',
        },
        problemTypeMap: {
          1: 'input', // 普通文本输入
          2: 'radio', // 单选
          3: 'checkbox', // 多选
          4: 'image-upload', // 图片上传
          7: 'textarea', // 多行文本输入
          8: 'draw', // 绘制多线
          10: 'draw', // 绘制多面
          11: 'building-choose', // 选择建筑物或楼栋-单个
          13: 'input', // 整数数字输入
          14: 'input', // 小数数字输入
          24: 'draw', // 绘制多点
          25: 'date-picker', // 日期选择
          26: 'region-select', // 级联筛选-行政区划选择-社区级别
          27: 'floor-choose', // 楼层选择
          28: 'region-select', // 级联筛选-行政区划选择-区级别
          29: 'region-select', // 级联筛选-行政区划选择-街道级别
          30: 'building-choose', // 选择建筑物或楼栋-多个
        },
        // 动态表单数据
        formData: {},
        formItems: [],
        formRules: {},
        currentDrawItem: null,
        // [POPUP_DRAWING] - 弹窗绘制相关
        showDrawTool: false,
        // [MAP_DRAWING] - 地图绘制相关（注释掉）
        isDrawingMode: false,
        drawEventListener: null,
        isBuildingSelectionMode: false,
        currentBuildingItem: null,
        selectedBuildings: [],
        specialLayerWasChecked: false,
      }
    },
    watch: {
      formData: {
        handler(newVal, oldVal) {
          this.$forceUpdate()
        },
        deep: true,
      },
    },
    methods: {
      openBuildingMode() {
        emitter.emit('ENABLE_BUILDING_CLICK')
      },
      closeBuildingMode() {
        emitter.emit('DISABLE_BUILDING_CLICK')
      },
      async handleImageUpload(file, fieldId) {
        const isImage = file.type.startsWith('image/')
        if (!isImage) {
          Message.error('只能上传图片文件!')
          return false
        }
  
        const isLt5M = file.size / 1024 / 1024 < 5
        if (!isLt5M) {
          Message.error('图片大小不能超过 5MB!')
          return false
        }
  
        try {
          const formData = new FormData()
          formData.append('file', file)
          formData.append('type', 'xcx')
  
          const response = await uploadFile(formData)
  
          if (response.success) {
            if (!Array.isArray(this.formData[fieldId])) {
              this.formData[fieldId] = []
            }
  
            this.formData[fieldId].push({
              name: file.name,
              url: URL.createObjectURL(file),
              uid: Date.now() + Math.random(),
              id: response.data,
            })
  
            Message.success('照片上传成功!')
          } else {
            Message.error(response.message || '上传失败')
          }
        } catch (error) {
          Message.error('上传失败，请重试')
        }
  
        return false
      },
  
      handleImageRemove(file, fieldId) {
        const index = this.formData?.[fieldId]?.findIndex(
          (item) => item.uid === file.uid
        )
        if (index > -1) {
          this.formData[fieldId].splice(index, 1)
          Message.success('照片删除成功!')
        }
      },
  
      handleStartDraw(item) {
        this.currentDrawItem = item
        
        // [POPUP_DRAWING] - 弹窗绘制模式（当前启用）
        this.showDrawTool = true
        
        // [MAP_DRAWING] - 地图绘制模式（注释掉）
        this.isDrawingMode = true
        const drawType = this.getDrawTypeFromProblemType(item.problemType)
        
        console.log('handleStartDraw - existing data:', {
          itemId: item.pkid,
          existingData: this.formData[item.pkid],
          drawType: drawType
        })
        
        emitter.emit('CLOSE_LEFT_PANEL')
        
        emitter.emit('START_MAP_DRAWING', {
          type: drawType,
          itemId: item.pkid,
          existingData: this.formData[item.pkid]
        })
        
        if (!this.drawEventListener) {
          this.drawEventListener = (data) => {
            if (data.itemId === item.pkid) {
              this.handleDrawEndNew(data)
            }
          }
          emitter.on('MAP_DRAWING_COMPLETE', this.drawEventListener)
        }
        
        Message.info(`请在地图上进行${item.problemContent}`)
      },
  
      handleViewDraw(item) {
        console.log('handleViewDraw', item)
        // this.currentDrawItem = item
        // this.showDrawTool = true
      },
  
      // [POPUP_DRAWING] - 处理弹窗关闭
      handleCloseDrawTool() {
        this.showDrawTool = false
        this.currentDrawItem = null
      },
  
      handleDrawEnd(data) {
        if (!this.currentDrawItem) return
  
        const { wgsPosition, lineWgsPosition, pointWgsPosition } = data
        let featureCount = 0
        let positionInfo = []
        let geoJsonFeature = null
  
        switch (this.currentDrawItem.problemType) {
          case '8':
            if (lineWgsPosition) {
              const lines = JSON.parse(lineWgsPosition)
              featureCount = lines.length
  
              geoJsonFeature = {
                type: 'Feature',
                properties: {},
                geometry: {
                  type: lines.length === 1 ? 'LineString' : 'MultiLineString',
                  coordinates: lines.length === 1 ? lines[0] : lines,
                },
              }
  
              positionInfo.push(`${lines.length} 条线`)
            }
            break
          case '10':
            if (wgsPosition) {
              const polygons = JSON.parse(wgsPosition)
              featureCount = polygons.length
              geoJsonFeature = {
                type: 'Feature',
                properties: {},
                geometry: {
                  type: polygons.length === 1 ? 'Polygon' : 'MultiPolygon',
                  coordinates:
                    polygons.length === 1
                      ? [polygons[0]]
                      : polygons.map((poly) => [poly]),
                },
              }
              positionInfo.push(`${polygons.length} 个面`)
            }
            break
          case '24':
            if (pointWgsPosition) {
              const points = JSON.parse(pointWgsPosition)
              featureCount = points.length
  
              const coordinates = points.map((point) => {
                if (Array.isArray(point) && point.length >= 2) {
                  return [parseFloat(point[0]), parseFloat(point[1])]
                }
                return point
              })
  
              geoJsonFeature = {
                type: 'Feature',
                properties: {},
                geometry: {
                  type: coordinates.length === 1 ? 'Point' : 'MultiPoint',
                  coordinates:
                    coordinates.length === 1 ? coordinates[0] : coordinates,
                },
              }
              positionInfo.push(`${coordinates.length} 个点`)
            }
            break
        }
  
        if (featureCount > 0 && geoJsonFeature) {
          this.formData[this.currentDrawItem.pkid] = geoJsonFeature
          Message.success(`成功绘制 ${positionInfo.join('、')}`)
        } else {
          this.formData[this.currentDrawItem.pkid] = ''
          Message.info('未绘制任何图形')
        }
  
        this.showDrawTool = false
        this.currentDrawItem = null
      },
  
      handleChooseBuilding(item) {
        this.openBuildingMode()
        if (this.isBuildingSelectionMode) {
          this.exitBuildingSelectionMode()
        }
  
        this.currentBuildingItem = item
  
        this.checkAndToggleSpecialLayer()
  
        this.isBuildingSelectionMode = true
  
        this.bindMapClickForBuildingSelection()
  
        Message.info('请在地图上点击选择楼栋，选择完成后点击"完成选中"按钮')
      },
  
      handleChooseFloor(item) {
        console.log('选择楼层:', item)
      },
  
      checkAndToggleSpecialLayer() {
        emitter.emit('CHECK_SPECIAL_LAYER_STATUS', (isChecked) => {
          this.specialLayerWasChecked = isChecked
  
          if (!isChecked) {
            emitter.emit('TOGGLE_SPECIAL_LAYER', true)
          }
        })
      },
  
      bindMapClickForBuildingSelection() {
        this.unbindMapClickForBuildingSelection()
        emitter.on('MAP_BUILDING_CLICK', this.handleBuildingClick)
      },
  
      unbindMapClickForBuildingSelection() {
        emitter.off('MAP_BUILDING_CLICK', this.handleBuildingClick)
      },
  
      handleBuildingClick(buildingData) {
        if (!this.isBuildingSelectionMode) return
  
        const existingIndex = this.selectedBuildings.findIndex(
          (building) => building.id === buildingData.id
        )
  
        if (existingIndex > -1) {
          this.selectedBuildings.splice(existingIndex, 1)
        } else {
          this.selectedBuildings.push(buildingData)
        }
  
        if (
          this.currentBuildingItem.problemType === '11' &&
          this.selectedBuildings.length > 1
        ) {
          this.selectedBuildings = [
            this.selectedBuildings[this.selectedBuildings.length - 1],
          ]
        }
  
        const buildingIds = this.selectedBuildings.map((building) => building.id)
        emitter.emit('UPDATE_SELECTED_BUILDINGS', buildingIds)
      },
  
      handleCompleteBuildingSelection(item) {
        this.closeBuildingMode()
        const buildSelectIds = this.selectedBuildings.map(
          (building) => building.id
        )
  
        this.formData[this.currentBuildingItem.pkid] = [{ buildings: buildSelectIds ,points:[]}]
  
        this.exitBuildingSelectionMode()
        Message.success(`已选择 ${this.selectedBuildings.length} 个楼栋`)
      },
  
      handleCancelBuildingSelection() {
        emitter.emit('CLEAR_SELECTED_BUILDINGS')
  
        this.selectedBuildings = []
  
        Message.info('已清空楼栋选择')
      },
  
      exitBuildingSelectionMode() {
        this.isBuildingSelectionMode = false
        this.currentBuildingItem = null
        this.unbindMapClickForBuildingSelection()
      },
  
      getBuildingCount(fieldId) {
        const data = this.formData[fieldId]
        if (!data) return 0
  
        try {
          const buildings = data[0].buildings
          return Array.isArray(buildings) ? buildings.length : 0
        } catch (e) {
          return 0
        }
      },
  
      handleSave() {
        this.$refs.editFormRef.validate((valid) => {
          if (valid) {
            // emitter.emit('REMOVE_SELECTED_BUILDINGS')
            emitter.emit('CLEAR_SELECTED_BUILDINGS')
            if (!this.specialLayerWasChecked) {
              emitter.emit('TOGGLE_SPECIAL_LAYER', false)
            }
  
            if (this.isBuildingSelectionMode) {
              this.exitBuildingSelectionMode()
            }
  
            const formatData = { ...this.formData }
            this.formItems.forEach((item) => {
              if (
                ['checkbox', 'region-select'].includes(item.type) &&
                Array.isArray(formatData[item.pkid])
              ) {
                formatData[item.pkid] = formatData[item.pkid].join(',')
              }
              if (
                item.type === 'image-upload' &&
                Array.isArray(formatData[item.pkid])
              ) {
                formatData[item.pkid] = formatData[item.pkid]
                  .map((img) => img.id)
                  .join(',')
              }
            })
  
            this.$emit('save', formatData)
          } else {
            Message.error('请检查表单输入！')
            return false
          }
        })
      },
  
      handleDelete() {
        this.$emit('delete')
      },
  
      handleCancel() {
        this.$emit('cancel')
      },
  
      resetForm() {
        this.formData = {}
        this.formItems = []
        this.formRules = {}
        this.$nextTick(() => {
          if (this.$refs.editFormRef) {
            this.$refs.editFormRef.clearValidate()
          }
        })
      },
  
      handleDrawEndNew(data) {
        if (!this.currentDrawItem || data.itemId !== this.currentDrawItem.pkid) return
  
        const { geoJsonFeature, featureCount, positionInfo } = data
  
        if (featureCount > 0 && geoJsonFeature) {
          this.formData[this.currentDrawItem.pkid] = geoJsonFeature
          Message.success(`成功绘制 ${positionInfo}`)
        } else {
          this.formData[this.currentDrawItem.pkid] = ''
          Message.info('未绘制任何图形')
        }
  
        this.cleanupDrawing()
        
        // Reopen the left panel
        emitter.emit('OPEN_LEFT_PANEL')
      },
      
      cleanupDrawing() {
        this.isDrawingMode = false
        this.currentDrawItem = null
        
        // Remove event listener
        if (this.drawEventListener) {
          emitter.off('MAP_DRAWING_COMPLETE', this.drawEventListener)
          this.drawEventListener = null
        }
        
        // Restore all catalog layers after drawing cleanup
        emitter.emit('RESTORE_ALL_CATALOG_LAYERS')
      },
      
      getDrawTypeFromProblemType(problemType) {
        switch (problemType) {
          case '8': return 'line'
          case '10': return 'polygon'
          case '24': return 'point'
          default: return 'polygon'
        }
      },
      
      handleCancelDrawing() {
        emitter.emit('STOP_MAP_DRAWING')
        this.cleanupDrawing()
        emitter.emit('OPEN_LEFT_PANEL')
        Message.info('已取消绘制')
      },
  
      getDrawMapData() {
        if (!this.currentDrawItem) return {}
  
        const fieldValue = this.formData[this.currentDrawItem.pkid]
        if (!fieldValue) return {}
  
        // 如果是 GeoJSON Feature 对象，转换为对应的位置格式
        if (typeof fieldValue === 'object' && fieldValue.type === 'Feature') {
          const geometry = fieldValue.geometry
          
          switch (this.currentDrawItem.problemType) {
            case '8': // 多线
              if (geometry.type === 'LineString') {
                return { lineWgsPosition: JSON.stringify([geometry.coordinates]) }
              } else if (geometry.type === 'MultiLineString') {
                return { lineWgsPosition: JSON.stringify(geometry.coordinates) }
              }
              break
            case '10': // 多面
              if (geometry.type === 'Polygon') {
                return { wgsPosition: JSON.stringify([geometry.coordinates[0]]) }
              } else if (geometry.type === 'MultiPolygon') {
                return { wgsPosition: JSON.stringify(geometry.coordinates.map(poly => poly[0])) }
              }
              break
            case '24': // 多点
              if (geometry.type === 'Point') {
                return { pointWgsPosition: JSON.stringify([geometry.coordinates]) }
              } else if (geometry.type === 'MultiPoint') {
                return { pointWgsPosition: JSON.stringify(geometry.coordinates) }
              }
              break
          }
          
          // 如果无法转换，仍然传递原始 GeoJSON
          return { geoJsonData: fieldValue }
        }
        
        // 如果是字符串，尝试解析
        if (typeof fieldValue === 'string') {
          try {
            const parsedValue = JSON.parse(fieldValue)
            if (parsedValue && parsedValue.type === 'Feature') {
              this.formData[this.currentDrawItem.pkid] = parsedValue
              return this.getDrawMapData()
            }
            else if (Array.isArray(parsedValue)) {
              switch (this.currentDrawItem.problemType) {
                case '8':
                  return { lineWgsPosition: fieldValue }
                case '10':
                  return { wgsPosition: fieldValue }
                case '24':
                  return { pointWgsPosition: fieldValue }
                default:
                  return {}
              }
            }
          } catch (e) {
            console.warn('Failed to parse draw data:', fieldValue)
          }
        }
  
        return {}
      },
  
      // 获取绘制状态文本
      getDrawStatusText(item) {
        const fieldValue = this.formData[item.pkid]
        if (!fieldValue) return ''
        
        try {
          let geoJsonData = null
          
          // 如果是 GeoJSON Feature 对象
          if (typeof fieldValue === 'object' && fieldValue.type === 'Feature') {
            geoJsonData = fieldValue
          }
          // 如果是字符串，尝试解析
          else if (typeof fieldValue === 'string') {
            const parsedValue = JSON.parse(fieldValue)
            if (parsedValue && parsedValue.type === 'Feature') {
              geoJsonData = parsedValue
            }
          }
  
          console.log('geoJsonData', geoJsonData)
          
          // 如果是 GeoJSON 格式，解析几何图形数量
          if (geoJsonData && geoJsonData.geometry) {
            const geometry = geoJsonData.geometry
            
            switch (geometry.type) {
              case 'Point':
                return '已绘制 1 个点'
              case 'MultiPoint':
                return `已绘制 ${geometry.coordinates.length} 个点`
              case 'LineString':
                return '已绘制 1 条线'
              case 'MultiLineString':
                return `已绘制 ${geometry.coordinates.length} 条线`
              case 'Polygon':
                return '已绘制 1 个面'
              case 'MultiPolygon':
                return `已绘制 ${geometry.coordinates.length} 个面`
              default:
                return '已绘制'
            }
          }
          
          // 兼容旧格式的数据
          if (typeof fieldValue === 'string') {
            const parsedValue = JSON.parse(fieldValue)
            if (Array.isArray(parsedValue)) {
              switch (item.problemType) {
                case '8': // 多线
                  return `已绘制 ${parsedValue.length} 条线`
                case '10': // 多面
                  return `已绘制 ${parsedValue.length} 个面`
                case '24': // 多点
                  return `已绘制 ${parsedValue.length} 个点`
                default:
                  return '已绘制'
              }
            }
          }
        } catch (e) {
          console.warn('Failed to parse draw status:', fieldValue)
        }
        
        return '已绘制'
      },
  
      cleanAreaListChildren(list) {
        if (!Array.isArray(list)) return
        list.forEach((item) => {
          if (Array.isArray(item.children)) {
            if (item.children.length === 0) {
              delete item.children
            } else {
              this.cleanAreaListChildren(item.children)
            }
          } else if (item.children == null) {
            delete item.children
          }
        })
      },
  
      initForm(formConfig) {
        this.formData = {}
        this.formItems = []
        this.formRules = {}
  
        if (!formConfig || !formConfig.length) return
  
        const sortedItems = formConfig.sort((a, b) => a.orderIndex - b.orderIndex)
  
        sortedItems.forEach((question) => {
          if (question.areaList) {
            this.cleanAreaListChildren(question.areaList)
          }
          this.formItems.push({
            ...question,
            type: this.problemTypeMap[question.problemType],
          })
  
          let initialValue = ''
          if (question.problemResult) {
            if (question.problemType === '3') {
              initialValue = question.problemResult.split(',')
            } else if (question.problemType === '4') {
              initialValue = question.filePaths
                ? this.parseFilePaths(question.filePaths)
                : []
            } else if (
              ['8', '10', '24', '11', '27', '30'].includes(question.problemType)
            ) {
              try {
                const parsedData = JSON.parse(question.problemResult)
                initialValue = parsedData
                this.initBuildingAndDraw(parsedData)
              } catch (e) {
                console.warn(
                  'Failed to parse problemResult JSON:',
                  question.problemResult
                )
                initialValue = ''
              }
            } else if (['26', '28', '29'].includes(question.problemType)) {
              initialValue = question.problemResult.split(',')
            } else {
              initialValue = question.problemResult
            }
          } else {
            if (question.problemType === '3') {
              initialValue = question.parentContentValue
                ? question.parentContentValue.split(',')
                : []
            } else if (question.problemType === '4') {
              initialValue = []
            } else if (
              ['8', '10', '24', '11', '27', '30'].includes(question.problemType)
            ) {
              initialValue = ''
            } else if (['26', '28', '29'].includes(question.problemType)) {
              initialValue = []
            } else {
              initialValue = question.parentContentValue || ''
            }
          }
  
          this.$set(this.formData, question.pkid, initialValue)
  
          if (question.children && question.children.length > 0) {
            this.processChildren(question.children, question.pkid)
          }
  
          if (question.requireStatus === '1') {
            this.$set(this.formRules, question.pkid, [
              {
                required: true,
                message: question.hint || `请输入${question.problemContent}`,
                trigger: ['blur', 'change'],
              },
            ])
  
            if (question.problemType === '13') {
              this.formRules[question.pkid].push({
                pattern: /^\d+$/,
                message: '请输入整数',
                trigger: 'blur',
              })
            } else if (question.problemType === '14') {
              this.formRules[question.pkid].push({
                pattern: /^\d+(\.\d+)?$/,
                message: '请输入数字',
                trigger: 'blur',
              })
            } else if (question.problemType === '4' && question.limitCondition) {
              this.formRules[question.pkid].push({
                validator: (rule, value, callback) => {
                  const minCount = parseInt(question.limitCondition)
                  const currentCount = Array.isArray(value) ? value.length : 0
                  if (currentCount < minCount) {
                    callback(new Error(`至少需要上传 ${minCount} 张照片`))
                  } else {
                    callback()
                  }
                },
                trigger: ['blur', 'change'],
              })
            }
          }
        })
  
        this.$nextTick(() => {
          if (this.$refs.editFormRef) {
            this.$refs.editFormRef.clearValidate()
          }
        })
      },
  
      processChildren(children, parentId) {
        children.forEach((child) => {
          if (child.areaList) {
            this.cleanAreaListChildren(child.areaList)
          }
          this.formItems.push({
            ...child,
            type: this.problemTypeMap[child.problemType],
            parentId: parentId,
            parentContentIndex: child.parentContentIndex,
          })
  
          let childInitialValue = ''
          if (child.problemResult) {
            if (child.problemType === '3') {
              childInitialValue = child.problemResult.split(',')
            } else if (child.problemType === '4') {
              childInitialValue = child.filePaths
                ? this.parseFilePaths(child.filePaths)
                : []
            } else if (
              ['8', '10', '24', '11', '27', '30'].includes(child.problemType)
            ) {
              try {
                const parsedChildData = JSON.parse(child.problemResult)
                childInitialValue = parsedChildData
                this.initBuildingAndDraw(parsedChildData)
              } catch (e) {
                console.warn(
                  'Failed to parse child problemResult JSON:',
                  child.problemResult
                )
                childInitialValue = ''
              }
            } else if (['26', '28', '29'].includes(child.problemType)) {
              childInitialValue = child.problemResult.split(',')
            } else {
              childInitialValue = child.problemResult
            }
          } else {
            if (child.problemType === '3') {
              childInitialValue = child.parentContentValue
                ? child.parentContentValue.split(',')
                : []
            } else if (child.problemType === '4') {
              childInitialValue = []
            } else if (
              ['8', '10', '24', '11', '27', '30'].includes(child.problemType)
            ) {
              childInitialValue = ''
            } else if (['26', '28', '29'].includes(child.problemType)) {
              childInitialValue = []
            } else {
              childInitialValue = child.parentContentValue || ''
            }
          }
  
          this.$set(this.formData, child.pkid, childInitialValue)
  
          if (child.children && child.children.length > 0) {
            this.processChildren(child.children, child.pkid)
          }
  
          if (child.requireStatus === '1') {
            this.$set(this.formRules, child.pkid, [
              {
                required: true,
                message: child.hint || `请输入${child.problemContent}`,
                trigger: ['blur', 'change'],
              },
            ])
  
            if (child.problemType === '13') {
              this.formRules[child.pkid].push({
                pattern: /^\d+$/,
                message: '请输入整数',
                trigger: 'blur',
              })
            } else if (child.problemType === '14') {
              this.formRules[child.pkid].push({
                pattern: /^\d+(\.\d+)?$/,
                message: '请输入数字',
                trigger: 'blur',
              })
            } else if (child.problemType === '4' && child.limitCondition) {
              this.formRules[child.pkid].push({
                validator: (rule, value, callback) => {
                  const minCount = parseInt(child.limitCondition)
                  const currentCount = Array.isArray(value) ? value.length : 0
                  if (currentCount < minCount) {
                    callback(new Error(`至少需要上传 ${minCount} 张照片`))
                  } else {
                    callback()
                  }
                },
                trigger: ['blur', 'change'],
              })
            }
          }
        })
      },
  
      initBuildingAndDraw(drawData) {
        if (drawData && drawData.type === 'Feature') {
          return
        }
  
        if (
          Array.isArray(drawData) &&
          drawData[0] &&
          drawData[0].buildings &&
          drawData[0].buildings.length
        ) {
          this.selectedBuildings = drawData[0].buildings.map((id) => {
            return {
              id: id,
              name: `楼栋${id}`,
              type: 'building',
              properties: { id: id },
              layerId: '',
              coordinates: null,
            }
          })
          this.checkAndToggleSpecialLayerForEcho(drawData[0].buildings)
        }
      },
  
      checkAndToggleSpecialLayerForEcho(buildingIds) {
        emitter.emit('CHECK_SPECIAL_LAYER_STATUS', (isChecked) => {
          this.specialLayerWasChecked = isChecked
  
          if (!isChecked) {
            emitter.emit('TOGGLE_SPECIAL_LAYER', true)
  
            setTimeout(() => {
              this.highlightAndLocateBuildings(buildingIds)
            }, 1000)
          } else {
            this.highlightAndLocateBuildings(buildingIds)
          }
        })
      },
  
      highlightAndLocateBuildings(buildingIds) {
        emitter.emit('UPDATE_SELECTED_BUILDINGS', buildingIds)
        emitter.emit('LOCATE_TO_BUILDINGS', buildingIds)
      },
  
      parseFilePaths(filePaths) {
        if (!Array.isArray(filePaths)) return []
        return filePaths.map((item, index) => ({
          name: item.fileName || `image_${index + 1}.jpg`,
          url: item.fileUrl,
          uid: item.pkid || Date.now() + index,
          id: item.pkid || item.fileUrl,
          raw: item,
        }))
      },
      removeFocusBeforeSwitch() {
        const el = document.activeElement
        if (el && el.tagName === 'INPUT' && el.type === 'radio') {
          el.blur()
        }
      },
      shouldShowChildItem(item) {
        this.removeFocusBeforeSwitch()
        if (
          !item.parentId ||
          item.parentContentIndex === null ||
          item.parentContentIndex === undefined
        ) {
          return true
        }
  
        const parentValue = this.formData[item.parentId]
  
        if (!parentValue) {
          return false
        }
  
        const parentItem = this.formItems.find(
          (formItem) => formItem.pkid === item.parentId
        )
        if (!parentItem || !parentItem.problemContentInfoList) {
          return false
        }
  
        const targetIndex = parseInt(item.parentContentIndex)
  
        if (parentItem.problemType === '2') {
          const selectedOption = parentItem.problemContentInfoList.find(
            (option) => option.pkid === parentValue
          )
          if (selectedOption) {
            return selectedOption.orderIndex === targetIndex
          }
        } else if (parentItem.problemType === '3') {
          if (Array.isArray(parentValue)) {
            return parentValue.some((value) => {
              const option = parentItem.problemContentInfoList.find(
                (opt) => opt.pkid === value
              )
              return option && option.orderIndex === targetIndex
            })
          }
        }
  
        return false
      },
      getRegionLabel(item, valueArr) {
        let options = item.areaList || this.cityOptions
        let labels = []
        let find = (opts, idx) => {
          if (!opts || idx >= valueArr.length) return
          let node = opts.find((o) => o.pkid == valueArr[idx])
          if (node) {
            labels.push(node.areaName)
            if (node.children && idx + 1 < valueArr.length) {
              find(node.children, idx + 1)
            }
          }
        }
        find(options, 0)
        return labels.join(' / ')
      },
    },
    beforeDestroy() {
      if (this.isBuildingSelectionMode) {
        this.exitBuildingSelectionMode()
      }
  
      emitter.emit('REMOVE_SELECTED_BUILDINGS')
      
      // [MAP_DRAWING] - 清理地图绘制相关（注释掉）
      if (this.isDrawingMode) {
        this.cleanupDrawing()
        emitter.emit('STOP_MAP_DRAWING')
      }
      
      if (this.drawEventListener) {
        emitter.off('MAP_DRAWING_COMPLETE', this.drawEventListener)
        this.drawEventListener = null
      }
    },
  }
  </script>
  
  <style lang="scss" scoped>
  .edit-mode {
    flex: 1;
    overflow-y: auto;
  
    .edit-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 16px 20px;
      border-bottom: 1px solid #e8e8e8;
  
      .edit-title {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        .edit-title-text {
          vertical-align: middle;
          display: inline-block;
          max-width: 240px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
  
        .edit-status {
          vertical-align: middle;
          border-radius: 4px;
          padding: 2px 4px;
          background: #e6f3ff;
          color: #fff;
          font-size: 12px;
          margin-left: 10px;
  
          &.add-status {
            background: #f6ffed;
            color: #52c41a;
          }
        }
      }
  
      .edit-subtitle {
        font-size: 12px;
        color: #999;
        margin-left: 8px;
      }
  
      .edit-actions {
        display: flex;
        gap: 8px;
      }
    }
  
    .edit-form {
      padding: 16px 20px;
  
      :deep(.el-form-item) {
        margin-bottom: 16px;
  
        .el-form-item__label {
          padding-bottom: 0;
        }
  
        .el-input {
          width: 100%;
          .el-input__inner {
            height: 32px;
            line-height: 32px;          
            &[type="number"] {
              -moz-appearance: textfield;
              &::-webkit-outer-spin-button,
              &::-webkit-inner-spin-button {
                -webkit-appearance: none;
                margin: 0;
              }
            }
          }
        }
  
        .el-textarea {
          width: 100%;
          .el-textarea__inner {
            padding: 8px 12px;
          }
        }
  
  
        .el-radio-group {
          display: flex;
          flex-wrap: wrap;
          gap: 16px;
          .el-radio {
            margin-right: 0;
            line-height: 1.4;
            white-space: normal;
            word-break: break-word;
            max-width: 355px;
            display: flex;
            align-items: flex-start;
            .el-radio__input {
              margin-top: 2px;
              flex-shrink: 0;
            }
            .el-radio__label {
              white-space: normal;
              word-break: break-word;
              line-height: 1.4;
              padding-left: 8px;
            }
          }
        }
  
        .el-checkbox-group {
          display: flex;
          flex-wrap: wrap;
          gap: 16px;
          .el-checkbox {
            margin-right: 0;
            line-height: 1.4;
            white-space: normal;
            word-break: break-word;
            max-width: 355px;
            display: flex;
            align-items: flex-start;
            .el-checkbox__input {
              margin-top: 2px;
              flex-shrink: 0;
            }
            .el-checkbox__label {
              white-space: normal;
              word-break: break-word;
              line-height: 1.4;
              padding-left: 8px;
            }
          }
        }
  
        .el-upload {
          &.el-upload--picture-card {
            width: 100px;
            height: 100px;
            line-height: 100px;
          }
        }
        .el-upload-list--picture-card {
          .el-upload-list__item {
            width: 100px;
            height: 100px;
            &.is-ready {
              display: none;
            }
          }
        }
  
        .el-button {
          min-width: 120px;
        }
  
        .el-cascader {
          width: 100%;
        }
      }
  
      .draw-info,
      .building-info,
      .floor-info {
        margin-left: 12px;
        font-size: 13px;
        color: #67c23a;
      }
  
      .building-selection-container {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 8px;
  
        .building-info {
          margin-left: 0;
          margin-top: 8px;
          font-weight: 500;
        }
  
        .el-button {
          min-width: 100px;
        }
      }
  
      .form-actions {
        display: flex;
        justify-content: center;
        gap: 12px;
        margin-top: 24px;
        padding-top: 16px;
        border-top: 1px solid #f0f0f0;
      }
  
      .upload-limit {
        font-size: 12px;
        color: #909399;
        margin-top: 8px;
        line-height: 1.4;
      }
    }
  }
  </style>
  